package gossip.v2.message;

import com.baidu.bjf.remoting.protobuf.annotation.ProtobufClass;
import gossip.v2.util.SerializationUtils;
import gossip.v2.cluster.GossipNode;
import lombok.Getter;
import java.util.Map;

@Getter
@ProtobufClass
public class AckMessage extends GossipMessage {
    private Map<String, byte[]> stateValues;
    private String targetNodeId;
    private Boolean alive;

    public AckMessage() {
        type = Type.ACK;
    }

    public AckMessage(GossipNode sender, Map<String, byte[]> stateValues) {
        this();
        setSender(sender);
        this.stateValues = stateValues;
    }

    public AckMessage(GossipNode sender, GossipNode targetNode, boolean isAlive) {
        this();
        setSender(sender);
        this.targetNodeId = targetNode != null ? targetNode.getNodeId() : null;
        this.alive = isAlive;
    }

    private void setSender(GossipNode sender) {
        this.sender = sender;
        this.senderId = sender != null ? sender.getNodeId() : null;
    }

    public <T> T getValueAs(String key, Class<T> clazz) {
        byte[] bytes = stateValues.get(key);
        return bytes != null ? SerializationUtils.deserialize(bytes, clazz) : null;
    }

    public boolean isIndirectResponse() {
        return targetNodeId != null;
    }
}
